/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.identity;

import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.CheckRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.CheckVo;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.type.IResponseMessage;
import org.apache.shiro.crypto.hash.SimpleHash;

import java.util.ArrayList;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class CheckCmd extends AbstractCommand<CheckRequestMessage> {

	/**
	 * @param req
	 */
	public CheckCmd(CheckRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		CheckVo ck = req.getBody();
		List<FieldDo> params = new ArrayList<FieldDo>();
		params.add(new FieldDo(FieldType.VARCHAR, ck.getUser()));
		SimpleHash hash = new SimpleHash("SHA-256", ck.getPassword(), null,
				1024);
		params.add(new FieldDo(FieldType.VARCHAR, hash.toBase64()));
		FieldDo field = cc
				.getBizDao()
				.selectObject(
						"select count(*) from sys_user_info where userId=? and password=? and state=1",
						params);
		Number num = (Number) field.getValue();
		if (num.intValue() == 1) {
			if (ck.getRoles() != null && ck.getRoles().length > 0) {
				StringBuilder sb = new StringBuilder(
						"select count(*) from sys_user_role_info where userId=? and roleId in (");
				params.clear();
				params.add(new FieldDo(FieldType.VARCHAR, ck.getUser()));
				for (int i = 0; i < ck.getRoles().length; i++) {
					params.add(new FieldDo(FieldType.VARCHAR, ck.getRoles()[i]));
					sb.append("?");
					if (i < ck.getRoles().length - 1)
						sb.append(",");
				}
				sb.append(")");
				field = cc.getBizDao().selectObject(sb.toString(), params);
				num = (Number) field.getValue();
				if (num.intValue() == 0)
					return new SimpleResponseMessage(false);
			}
			if (!Strings.isBlank(ck.getToField()))
				cc.getWorkflowContext().getRecord()
						.setValue(ck.getToField(), ck.getUser());
			return new SimpleResponseMessage(true);
		}
		return new SimpleResponseMessage(false);
	}

}
